package com.wanban.downloader.manager

import android.util.Log
import com.blankj.utilcode.util.NetworkUtils
import com.tencent.rtmp.TXLiveBase
import com.tencent.rtmp.TXLiveConstants
import com.tencent.rtmp.TXPlayerGlobalSetting
import com.tencent.rtmp.downloader.ITXVodDownloadListener
import com.tencent.rtmp.downloader.TXVodDownloadManager
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_403FORBIDDEN
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_AUTH_FAILED
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_DISCONNECT
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_FORMAT_ERROR
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_HLS_KEY_ERROR
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_NO_FILE
import com.tencent.rtmp.downloader.TXVodDownloadManager.DOWNLOAD_PATH_ERROR
import com.tencent.rtmp.downloader.TXVodDownloadMediaInfo
import com.wanban.downloader.db.DownloadEntity
import com.wanban.downloader.listener.OnDownloadListener
import com.wanban.downloader.model.DownloadType
import com.wanban.downloader.utils.FileDownloadPathUtils


class TXDownloadManager(listener: OnDownloadListener?): BaseDownloadManager(listener), ITXVodDownloadListener {

    private val preferredResolution = 1920 * 1080L
    private var downloader = TXVodDownloadManager.getInstance()

    override fun getDownloadType(): Int {
        return DownloadType.TX
    }

    init {
        // 若您服务全球用户， 配置 SDK 接入环境为全球接入环境
        TXLiveBase.setGlobalEnv("GDPR")
        // 设置log
        TXLiveBase.setLogLevel(TXLiveConstants.LOG_LEVEL_WARN)
        // 设置下载路径
        val path = FileDownloadPathUtils.getOrCreateDownloadRootFileDirPath()
        TXPlayerGlobalSetting.setCacheFolderPath("$path/tx_download")
        Log.e("TXDownloadManager", "下载目录 -> $path" )
        downloader.setListener(this)
    }

//    override fun init(application: Application, listener: OnDownloadListener?) {
//        super.init(application, listener)
//        // 若您服务全球用户， 配置 SDK 接入环境为全球接入环境
//        TXLiveBase.setGlobalEnv("GDPR")
//        // 设置log
//        TXLiveBase.setLogLevel(TXLiveConstants.LOG_LEVEL_WARN)
//        // 设置下载路径
//        val path = FileDownloadPathUtils.getOrCreateDownloadRootFileDirPath()
//        TXPlayerGlobalSetting.setCacheFolderPath("$path/tx_download")
//        Log.e("TXDownloadManager", "下载目录 -> $path" )
//        downloader.setListener(this)
//    }

    override fun executeStart(task: DownloadEntity) {
        // 开始启动下载
        downloader.startDownloadUrl(task.url, preferredResolution, task.getFileName())
    }

    override fun stopDownloadTask(url: String) {
        val downloadInfo = downloader.downloadMediaInfoList.firstOrNull { it.url == url }?:return
        downloader.stopDownload(downloadInfo)
    }

    override fun deleteTaskFile(task: DownloadEntity) {
        val downloadInfo = downloader.downloadMediaInfoList.firstOrNull { it.url == task.url }?:return
        downloader.deleteDownloadMediaInfo(downloadInfo)
    }

    override fun onDownloadStart(p0: TXVodDownloadMediaInfo) {
        onStartStatus(p0.url)
    }

    override fun onDownloadProgress(p0: TXVodDownloadMediaInfo) {
        // url: String, speed: Long, percent: Float, currentLength: Long
        onProgressStatus(p0.url, p0.speed.toLong() * 1024, p0.progress * 100, p0.downloadSize)
    }

    override fun onDownloadStop(p0: TXVodDownloadMediaInfo) {
        onStopStatus(p0.url, false)
    }

    override fun onDownloadFinish(p0: TXVodDownloadMediaInfo) {
        val task = getTaskByUrl(p0.url)?:return
        task.filePath = p0.playPath
        onSuccessStatus(task)
    }

    override fun onDownloadError(p0: TXVodDownloadMediaInfo, p1: Int, p2: String) {
        Log.e("TXDownloader", "onDownloadError: $p1, $p2")
        val task = getTaskByUrl(p0.url)?:return
        val errorMessage = when (p1){
            DOWNLOAD_AUTH_FAILED -> "向云点播控制台请求视频信息失败，建议检查fileId、psign参数是否正确。"
            DOWNLOAD_NO_FILE -> "无此清晰度文件。"
            DOWNLOAD_FORMAT_ERROR -> "下载文件格式不支持。"
            DOWNLOAD_DISCONNECT -> {
                if (NetworkUtils.isConnected()) {
                    "下载失败，请稍后重试！"
                } else {
                    "网络断开，建议检查网络是否正常。"
                }
            }
            DOWNLOAD_HLS_KEY_ERROR -> "获取 HLS 解密 Key 失败。"
            DOWNLOAD_PATH_ERROR -> "下载目录访问失败，建议检查是否有访问下载目录的权限。"
            DOWNLOAD_403FORBIDDEN -> "请求下载时，鉴权信息不通过，建议检查签名(psign) 是否已过期。"
            else -> "下载成功。"
        }
        task.errorMsg = errorMessage

        if (p1 == DOWNLOAD_DISCONNECT && !NetworkUtils.isConnected()) {
            task.isNetworkError = true
            onPendingStatus(task)
        } else {
            onErrorStatus(task)
        }
    }

    override fun hlsKeyVerify(p0: TXVodDownloadMediaInfo, p1: String?, p2: ByteArray?): Int {
        return 0
    }

}